using System.Threading;
using Eclipse.TRCore.Http;
using Eclipse.TRCore.Model;

namespace Eclipse.TRCore.Travians.Tasks
{
    public abstract class TravianTask : IExecutable
    {
        public HttpConfig HttpConfig;
        public IAction FirstAction;
        public IAction LastAction
        {
            get
            {
                if (null == FirstAction)
                    return null;
                IAction action = FirstAction;
                while (null != action.NextAction)
                {
                    action = action.NextAction;
                }
                return action;
            }
        }
        protected abstract void Init();
        protected virtual void LinkDynamicAction(IAction executedAction){}
        #region IExecutable Members

        private volatile IAction currExecAction;
        private long stoplock = -1;
        public void Execute()
        {
            currExecAction = null;
            Init();
            IAction action = FirstAction;
            while(Interlocked.Read(ref stoplock) == -1)
            {
                currExecAction = action;

                if (action is IHttpAction)
                    ((IHttpAction)action).HttpConfig = HttpConfig;

                action.Execute();
                if (null != action.NextAction)
                    action = action.NextAction;
                else
                {
                    LinkDynamicAction(action);
                    if (null == action.NextAction)
                        break;
                }
            }
            Interlocked.Exchange(ref stoplock, -1);
            currExecAction = null;
        }

        public void Abort()
        {
            Interlocked.Exchange(ref stoplock, 0);
            if(null != currExecAction)
                currExecAction.Abort();
            currExecAction = null;
        }

        #endregion
    }
}
